import os
from alipay import AliPay
from django import http
from django.conf import settings
from django.db.utils import DataError
from django.http import JsonResponse
from django.shortcuts import render
from django.utils import timezone
from .models import OrderInfo, Payment
from mgproject.utils.views import LoginRequiredJSONMixin
# Create your view here.
from django.views import View
import json

class PaymentStatusView(LoginRequiredJSONMixin,View):
    def get(self,request):
        '''
        查询并保存结果
        :param self:
        :param request:
        :return:
        '''

        # 接收参数
        params_dict = request.GET.dict()
        # 校验参数（验证签名：判断是不是支付宝平台重定向过来的）
        sign = params_dict.pop('sign')

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认会调url
            app_private_key_string=open(
                os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem')).read(),
            alipay_public_key_string=open(
                os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/alipay_public_key.pem')).read(),
            sign_type='RSA2',
            debug=settings.ALIPAY_DEBUG
        )
        # 校验
        flag = alipay.verify(params_dict,sign)
        if flag:
            # 判断是否是正常请求

            # 获取订单号
            order_id = params_dict.get('out_trade_no')
            # 获取支付宝交易流水号
            trade_no = params_dict.get('trade_no')
            # 保存支付结果
            try:
                Payment.objects.create(order_id=order_id,trade_id=trade_no)
            except DataError:
                return http.HttpResponseForbidden('保存支付结果失败')

            # 更新订单表支付结果
            OrderInfo.objects.filter(order_id=order_id,status=1).update(status=2)

            # 响应页面结果
            return render(request,'payment/pay_success.html',{'trade_no':trade_no})
        else:
            return http.HttpResponseForbidden('非正常请求！')


class PaymentView(LoginRequiredJSONMixin,View):
    def post(self,request):
        '''获取支付宝扫码连接'''
        # 接受参数
        # 校验参数'{"key":"value}' --> {"key":"value"}
        params = request.body.decode()
        if not params:
            return JsonResponse({'code':4001,'errormsg':'缺少参数'})

        parsms_dict = json.loads(params)
        print(parsms_dict)

        artcile_id = parsms_dict['article_id']
        pay_method = parsms_dict['pay_method']
        total_amount = parsms_dict['pay_amount']
        user_id = int(parsms_dict['user_id'])

        # 生成订单
        # user_id = request.uesr_id

        # 生成订单编号：年月日时分秒+用户编号
        order_id = timezone.localtime().strftime('%Y%m%d%H%M%S')+('%03d' % user_id)  # %03d 取三位用户id

        # 调用支付接口过去支付连接地址
        try:
            order = OrderInfo.objects.create(order_id=order_id,user_id=user_id,pay_method=pay_method,total_amount=total_amount,article_id=artcile_id)
        except DataError:
            return JsonResponse({'code':4002,'errormsg':'生成订单失败'})

        # 调用支付宝接口获取支付连接地址
        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None, # 默认会调url
            app_private_key_string=open(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),'keys/app_private_key.pem')).read(),
            alipay_public_key_string=open(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),'keys/alipay_public_key.pem')).read(),
            sign_type='RSA2',
            debug=settings.ALIPAY_DEBUG
            )

        # 生成登录支付宝连接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject='芒果头条%s' % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
            notify_url=settings.ALIPAY_RETURN_URL,
        )

        # 响应结果
        # 响应登录支付宝链接
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return JsonResponse({'code':200,'errormsg':'ok','alipay_url':alipay_url})